import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class TextFieldComponent extends StatefulWidget {
  const TextFieldComponent({
    super.key,
    this.placeholder,
    this.controller,
    this.keyboardType = TextInputType.text,
    this.isPassword = false,
    this.maxLength,
    this.focusNode,
    this.inputFormatters,
    this.textAlign = TextAlign.left,
    this.maxLines = 1,
    this.textColor = Colors.black,
    this.cursorColor = Colors.blue,
    this.placeholderTextStyle,
    this.enable = true,
    this.fontSize = 16,
    this.backgroundColor = Colors.transparent,
    this.borderRadius,
    this.border,
    this.padding = const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
    this.margin,
    this.prefix,
    this.suffix,
    this.isShowClear = true,
    this.counter,
    this.onTap,
    this.onTapOutside,
    this.onChange,
    this.onComplete,
    this.crossAxisAlignment = CrossAxisAlignment.center,
  });

  /// 站位字符
  final String? placeholder;

  /// 控制器
  final TextEditingController? controller;

  /// 键盘类型（默认 text）
  final TextInputType keyboardType;

  /// 是否是密码（默认false）
  final bool isPassword;

  /// 最大长度
  final int? maxLength;

  /// 聚焦
  final FocusNode? focusNode;

  /// 输入格式化
  final List<TextInputFormatter>? inputFormatters;

  /// 字体对齐（默认 left）
  final TextAlign textAlign;

  /// 最大行数（默认 1，为null时自适应高度）
  final int? maxLines;

  /// 文字颜色（默认 black）
  final Color textColor;

  /// 光标颜色（默认 blue）
  final Color cursorColor;

  /// 站位字符样式
  final TextStyle? placeholderTextStyle;

  /// 交互（默认 true）
  final bool enable;

  /// 字体大小（默认 14）
  final double fontSize;

  /// 背景色（默认 white）
  final Color backgroundColor;

  /// 圆角
  final BorderRadiusGeometry? borderRadius;

  /// 边框
  final BoxBorder? border;

  /// 内边距（默认 EdgeInsets.symmetric(horizontal: 10, vertical: 4)）
  final EdgeInsetsGeometry? padding;

  /// 外边距
  final EdgeInsetsGeometry? margin;

  /// 头部组件
  final Widget? prefix;

  /// 尾部组件
  final Widget? suffix;

  /// 底部描述
  final Widget? counter;

  /// 点击回调
  final VoidCallback? onTap;

  /// 点击回调
  final void Function(PointerDownEvent event)? onTapOutside;

  /// 输入改变回调
  final Function(String text)? onChange;

  /// 输入完成回调
  final VoidCallback? onComplete;

  final CrossAxisAlignment crossAxisAlignment;

  final bool isShowClear;

  @override
  State<TextFieldComponent> createState() => _TextFieldComponentState();
}

class _TextFieldComponentState extends State<TextFieldComponent> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: widget.padding,
      margin: widget.margin,
      decoration: BoxDecoration(
        color: widget.backgroundColor,
        borderRadius: widget.borderRadius,
        border: widget.border,
      ),
      child: Row(
        crossAxisAlignment: widget.crossAxisAlignment,
        children: [
          widget.prefix == null ? const SizedBox.shrink() : widget.prefix!,
          Expanded(
            child: TextFormField(
              maxLines: widget.maxLines,
              maxLength: widget.maxLength,
              cursorColor: widget.cursorColor,
              obscureText: widget.isPassword,
              autocorrect: false,
              controller: widget.controller,
              keyboardType: widget.keyboardType,
              keyboardAppearance: Brightness.light,
              focusNode: widget.focusNode,
              inputFormatters: widget.inputFormatters,
              textAlign: widget.textAlign,
              enabled: widget.enable,
              style: TextStyle(
                textBaseline: TextBaseline.alphabetic,
                color: widget.textColor,
                fontSize: widget.fontSize,
              ),
              // textAlignVertical: TextAlignVertical.top,
              decoration: InputDecoration(
                hintText: widget.placeholder,
                counter: widget.counter,
                counterText: widget.counter == null ? '' : null,
                isCollapsed: true,
                contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 0),
                hintStyle: widget.placeholderTextStyle ?? const TextStyle(color: Colors.black26, fontSize: 16),
                border: InputBorder.none,
                prefix: null,
                suffix: widget.suffix ??
                    (widget.isShowClear && widget.controller?.text.length != 0 ? _buildClearButton() : null),
                isDense: true,
              ),
              onTap: widget.onTap,
              onTapOutside: widget.onTapOutside,
              onChanged: widget.onChange,
              onEditingComplete: widget.onComplete,
            ),
          ),
          widget.suffix == null ? const SizedBox.shrink() : widget.suffix!,
        ],
      ),
    );
  }

  Widget _buildClearButton() {
    return SizedBox(
      width: 20,
      height: 20,
      child: IconButton(
        padding: const EdgeInsets.all(0),
        alignment: Alignment.center,
        onPressed: () => _onClearButtonTap(),
        icon: Icon(Icons.cancel, size: 18, color: Color(0xFF999999)),
      ),
    );
  }

  void _onClearButtonTap() {
    widget.controller?.text = '';
    if (mounted) setState(() {});
    widget.focusNode?.requestFocus();
  }
}
